#include "../logs/log.h"

// 4. 自定义滚动  （以时间进行滚动）
class RollByTimeSink : public log::Sink
{
public:
    RollByTimeSink(const std::string &basename, size_t time_gap)
        : _basename(basename), _time_gap(time_gap), _start_time(0)
    {
        // 创建日志文件拓展名
        std::string pathname = createNewFile();
        // 1. 创建日志文件路径
        log::util::File::createDirectory(log::util::File::Path(pathname));
        // 2. 创建并打开日志文件
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    // 根据时间间隔进行新文件创建
    void log(const char *data, size_t len) override
    {
        if (_start_time == 0)
            _start_time = log::util::Date::now();

        // 每过time_gap就新建
        if (log::util::Date::now() - _start_time >= _time_gap)
        {
            _ofs.close(); // 一定要关闭原来的文件，否则会造成资源泄露
            std::string pathname = createNewFile();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _start_time = 0;
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile() // 以时间来构造文件拓展名
    {
        struct tm t;
        time_t now = log::util::Date::now();
        localtime_r(&now, &t);
        std::stringstream fs;
        // 年月日时分秒
        fs << _basename;
        fs << t.tm_year + 1900;
        fs << t.tm_mon + 1;
        fs << t.tm_mday;
        fs << t.tm_hour;
        fs << t.tm_min;
        fs << t.tm_sec;
        fs << ".log";
        return fs.str();
    }

private:
    std::string _basename; // 基础文件名 ./logs/base-    -->  ./log/base-当前时间.log
    std::ofstream _ofs;    // 操作句柄，每次将数据放入文件流中
    size_t _time_gap;      // 时间间隔
    size_t _start_time;    // 开始时间
};

int main()
{
    std::unique_ptr<log::LoggerBuilder> builder(new log::GlobalLoggerBuilder());
    builder->buildLoggerName("asycn_logger");
    builder->buildLoggerLevel(log::Level::value::DEBUG);
    builder->buildLoggerType(log::LoggerType::ASYNC_LOGGER);
    builder->buildFormatter();
    builder->buildSink<RollByTimeSink>("./logfile/rollTimeGap-", 1);
    log::Logger::ptr logger = builder->build();
    // 指定前缀名为./logfile/rollTimeGap-，一秒新建一个日志文件
    time_t t = log::util::Date::now();
    while (log::util::Date::now() - t < 5) // 写5秒数据，预期5个文件
    {
        logger->info(__FILE__, __LINE__, "日志落地拓展测试...%d", log::util::Date::now() - t);
    }
    return 0;
}